package com.linan.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Properties;

public enum RedisUtils {
    INSTANCE;
    static JedisPool jedisPool = null;
    static {
        // 創建连接池
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxIdle(2);
        config.setMaxTotal(10);
        config.setMaxWaitMillis(10*1000L);
        config.setTestOnBorrow(true);

        Properties properties = null;
        try {
             properties =new Properties();
             properties.load(RedisUtils.class.getClassLoader().getResourceAsStream("redis.properties"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        String host = properties.getProperty("redis.host");
        String port = properties.getProperty("redis.port");
        String password = properties.getProperty("redis.password");
        String timeout = properties.getProperty("redis.timeout");
       jedisPool = new JedisPool(config, host, Integer.valueOf(port), Integer.valueOf(timeout),password);
        Jedis jedis = jedisPool.getResource();
        jedis.set("heloJedis", "HelloJdeis");
        String result = jedis.get("heloJedis");
        System.out.println(result);
        // 关闭连接
//        jedis.close();

//        jedisPool.destroy();
    }


    // 获取连接池
    public Jedis getSource(){
        return  jedisPool.getResource();
    }

    // 关闭资源
    public void closeResource(Jedis jedis){
        if(jedis !=null){
            jedis.close();
        }
    }

    // 删除key
    public void del(String key ){
        Jedis jedis = getSource();
        jedis.del(key);
        closeResource(jedis);
    }

    // 设置值
    public void set(String key ,String value){
        Jedis jedis = getSource();
        jedis.set(key, value);
        closeResource(jedis);
    }
    // 获取值
    public String get(String key ){
        Jedis jedis = getSource();
        try {
            return jedis.get(key);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            closeResource(jedis);
        }
    }

    public void  set (String key,String value,Integer time){
        Jedis jedis = getSource();
        jedis.setex(key, time, value);
        closeResource(jedis);
    }






}
